﻿using System.IO;
using System.Runtime.Serialization.Formatters.Binary;

namespace Lucene.Linq.Storage
{
    /// <summary>
    /// Serializer for entities
    /// </summary>
    /// <typeparam name="T">Type of entity being serialized</typeparam>
    public class EntitySerializer<T>
        where T : IEntity, new()
    {
        private readonly BinaryFormatter _formatter;

        /// <summary>
        /// Default Constructor
        /// </summary>
        public EntitySerializer()
        {
            _formatter = new BinaryFormatter();
        }

        /// <summary>
        /// Deserialize the object from array of bytes into actual object
        /// </summary>
        /// <param name="data">data to deserialize</param>
        /// <returns>Data as actual object using BinaryFormatter</returns>
        public T Deserialize(byte[] data)
        {
            using (MemoryStream ms = new MemoryStream(data))
            {
                return _formatter.Deserialize(ms) is T ? (T)_formatter.Deserialize(ms) : default(T);
            }
        }

        /// <summary>
        /// Serialize the object into array of bytes
        /// </summary>
        /// <param name="data">Data to serialize</param>
        /// <returns>Data as array of bytes using BinaryFormatter</returns>
        public byte[] Serialize(T data)
        {
            using (MemoryStream ms = new MemoryStream())
            {
                _formatter.Serialize(ms, data);
                return ms.ToArray();
            }
        }
    }
}
